package leetCode.ergodic;

/**
 * 反转链表
 */
public class ReverseList {
    public static void main(String[] args) {
        ListNode pre = null;
        for (int i = 5; i > 0; i--) {
            ListNode temp = new ListNode();
            temp.val = i;
            temp.next = pre;
            pre = temp;
        }

        System.out.println("输入:" + pre.toString());
        ListNode listNode = reverseList2(pre);
        System.out.println("输出:" + listNode.toString());
    }

    public static ListNode reverseList(ListNode head) {
        ListNode pre = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }

    public static ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode pre = null;
        ListNode temp = head.next;
        head.next = pre;
        pre = head;
        reverseList2(head.next);
        return pre;
    }


    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }

        public ListNode() {
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
